//初始化全局的基础单位
document.documentElement.style.fontSize = document.documentElement.clientWidth / 10.8 + 'px';    
//返回键监听事件
   document.addEventListener('plusready', function(){
       plus.key.addEventListener('backbutton', function() {
        //返回键执行的内容
        if($('.play').position().top == 0){
            $('.play').css({top:'-100rem'});
            $('.main').css({top:'0'});
        }else{
            plus.runtime.quit(); 
        }
    }, false);
   });
//JQuery入口函数
$(function(){
    var Main ={};
    Main.page = 1;
    Main.content = '';
    Main.ip = false;
    
    Main.offsetLeft_scrollLeft = parseInt(document.documentElement.clientWidth / 10.8 * 3.3);
    Main.itemsList = document.getElementsByClassName('musicItem');
    Main.scrollIndex = 0;
    Main.scrollTimeOut;
    Main.clickN_PTimeout;


    var player = new Player($('audio'));
    var progress = new Progress($('.progressBar'),$('.progressIn'),$('.progressSpot'));
    
    progress.progressMove(function(value){
        player.getMusicInfo(function(a,b,c){
                player.setCurrentTime(value*b);
        })
    });
    player.musicUpdate(()=>{
        //获取播放器播放时间信息
        player.getMusicInfo((currentTime,duration,formatData)=>{
            //修改播放界面的播放时间
            $('.startTime').text(formatData.currentTime);
            //修改进度条
            progress.setProgress(Number(currentTime/duration).toFixed(4)*$('.progressBar').get(0).offsetWidth);
        })
    });
    player.play(()=>{
        //播放开始，给控件家动画
        $('.playBotton').addClass('rotate2');
        $('.playBotton').attr('src',player.musicList[player.now_index].img_url)
        $('.buttonPlay').addClass('pause');
        $(Main.itemsList[player.now_index]).find('img').addClass('rotate');
        $(Main.itemsList[player.now_index]).siblings().find('img').removeClass('rotate');
        moveScroll(player.now_index);
    });
    player.pause(()=>{
        //播放开始，给控件家动画
        $('.playBotton').removeClass('rotate2');
        $('.buttonPlay').removeClass('pause');
        $(Main.itemsList[player.now_index]).find('img').removeClass('rotate');
        
        //暂停且播放完毕，自动进行下一首
        if($('audio').get(0).ended){
            player.playMusic(player.nextMusic());
        }
    })
    player.loadedMetaData(()=>{
         //获取播放器播放时间信息
         player.getMusicInfo((currentTime,duration,formatData)=>{
            $('.totalDuration').text(formatData.duration);
         });
    });
   
   

    //搜索框的搜索
    //1、绑定按钮点击事件
    $('#searchBotton').on('click',function(){
        $('#searchBotton').addClass('click_bg');
        setTimeout(function(){
            $('#searchBotton').removeClass('click_bg');
        },100);
        if(!Main.ip){
            //限制多次点击
            Main.ip = true;
            //2、获取搜索框的内容，判断内容是否为合法
            var content = $("#searchTxt").val().trim();
            if(content){
                //3、判断当前搜索是否是上次搜索，
                if(content == Main.content){
                    //如果是，搜索下一页
                    Main.page++;
                }else{
                    //如果不是,重置页数，重新搜索，重新显示
                    Main.page = 1;
                    //将搜索的内容储存起来
                    Main.content = content;
                    //清空音乐列表
                    player.musicList.splice(0,player.musicList.length);
                    //重置nowindex
                    player.now_index = -1;
                    //重置Main.scrollIndex = 0;
                    Main.scrollIndex = 0;
                    //清空播放界面列表
                    $('.musicList').html('');
                }
                //4、发送ajax请求
                searchMusic(content,function(dataList){
                    //数据处理
                    if(dataList){
                        var list = dataHandle(dataList)
                        player.musicList = player.musicList.concat(list);
                        var $JQobj = tempalteFill('searchTempalte',list);
                        masonry($JQobj);
                        $JQobj = tempalteFill('playTempalte',list);
                        $('.musicList').append($JQobj);
                    }else{
                        Main.page--;
                    }
                    if(player.now_index == -1){
                        //放大第一项
                        $(Main.itemsList[0]).addClass('enlarge');
                        //载入第一首歌
                        player.getMusic(player.musicList[0].mid,function(url){
                                $('audio').attr('src',url);
                        })
                        //设置当前播放位置
                        player.now_index = 0;
                    }
                });
            }
            Main.ip = false;
        }
    });
    //2、绑定音乐列表项的点击事件
    $('.searchList').delegate('.searchItem','click',function(e){
        player.playMusic($(e.target).parent().index());
    })
    //3、绑定播放界面的按钮点击事件
    $('.playBottonMark').on('click',function(){
        if(!$('.main').position().top){
            $('.main').css({
                top:'-100rem'
            })
            $('.play').css({
                top:'0'
            })
        }
    });
    //4、搜索框按下enter键进行搜索
    $('#searchTxt').on('keydown',function(e){
        if (e.keyCode == 13) {
            $('#searchBotton').trigger('click');
        }
    });
    //5、绑定点击上下一曲事件 
    $('.preBotton').on('click',function(){
        $(this).addClass('shallow');
        player.playMusic(player.preMusic());
        setTimeout(function(){
            $('.preBotton').removeClass('shallow');
        },100)
    });
    $('.nextBotton').on('click',function(){
        $(this).addClass('shallow');
        player.playMusic(player.nextMusic());
        setTimeout(function(){
            $('.nextBotton').removeClass('shallow');
        },100)
    });
    $('.buttonPre').on('click',function(){
        $(this).addClass('shallow')
        if(--Main.scrollIndex < 0){
            Main.scrollIndex = Main.itemsList.length - 1;
        }
        moveScroll(Main.scrollIndex);
        if(Main.clickN_PTimeout){
            clearTimeout(Main.clickN_PTimeout);
        }
        Main.clickN_PTimeout = setTimeout(()=>{
            if(Main.scrollIndex != player.now_index){
                player.playMusic(Main.scrollIndex);
            }
        },1000)
        setTimeout(function(){
            $('.buttonPre').removeClass('shallow');
        },100)
    })
    $('.buttonNext').on('click',function(){
        $(this).addClass('shallow');
        if(++Main.scrollIndex >= Main.itemsList.length){
            Main.scrollIndex = 0;
        }
        moveScroll(Main.scrollIndex);
        if(Main.clickN_PTimeout){
            clearTimeout(Main.clickN_PTimeout);
        }
        Main.clickN_PTimeout = setTimeout(()=>{
            if(Main.scrollIndex != player.now_index){
                player.playMusic(Main.scrollIndex);
            }
        },1000)
        setTimeout(function(){
            $('.buttonNext').removeClass('shallow');
        },100)
    });
    //6、播放界面播放按钮点击事件
    $('.buttonPlay').on('click',function(){
        if(player.now_index != -1){
            player.playMusic(player.now_index);
        }
    });
    //7、播放界面滑动
    $('.musicBox').on('scroll',function(){
        computeDistance();
    });
    //8、播放界面的音乐项点击事件
    $('.musicList').delegate('.musicItem','click',function(e){
        if(e.target.tagName == 'IMG'){
            player.playMusic($(e.target).parent().index());
        }
    });
  
        
   //音乐查询发送ajax请求
    function searchMusic(name , callbacks) {
        $.ajax({
            url: 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p='+Main.page+'&n=20&w=' + name +'&g_tk=5381&loginUin=0&hostUin=0&format=jsonp&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq&needNewCode=0',
            type: 'get',
            dataType: 'jsonp',
            jsonpCallback: 'callback',
            success: function(data) {
                callbacks(data.data.song.list);
            },
            error:function(a){
                popup('搜索失败');
            }
        });
    }
    //数据处理函数
    function dataHandle(data){
        var objList = [];
        $.each(data, function(index,value){ 
            var obj = {};
            var singer = '';
            for (var j = 0; j < value.singer.length; j++) {
                singer += value.singer[j].name + ' ';
            }
            obj.singer = singer;
            obj.song = value.name;
            obj.filemid = value.file.media_mid;
            if (value.album.mid) {
                obj.img_url = 'https://y.gtimg.cn/music/photo_new/T002R300x300M000' + value.album.mid +'.jpg?max_age=2592000';
            } else {
                obj.img_url = './img/icon.jpg';
            }
            obj.mid = value.mid;
            objList.push(obj);
            
        });
        return objList;
    }
    //模板填充
    function tempalteFill(id,data){
        var content = '';
        $.each(data,function(index, value){
            content += tempalte(id,value);
        });
        //得到一大串字符串，将其装换成JQuery对象
        return $(content);
    }
    //列表瀑布流添加
    function masonry($JQobj){
        if(Main.page == 1 ){
            $('.searchList').html($JQobj);
            Main.masonry = new Masonry('.searchList',{});
        }else{
            $.each($JQobj,function(index,value){
                Main.masonry.element.appendChild(value);
                Main.masonry.appended(value);
            })
        }
    }
    //计算播放界面音乐列表项的放大后的位置
    function computeDistance(){
        if(Main.scrollTimeOut){
            clearTimeout(Main.scrollTimeOut);
        }
        //延迟设置滚动条;
        Main.scrollTimeOut = setTimeout(function(){
             //放大index
        $(Main.itemsList[Main.scrollIndex]).addClass('enlarge');
        //缩小其他
        $(Main.itemsList[Main.scrollIndex]).siblings().removeClass('enlarge');
            moveScroll(Main.scrollIndex);
        },50);
        //滚动条滚动的距离
        Main.scrollIndex = computeCenterIndex();
       
    }
    //移动滚动条
    function moveScroll(index){
        var distance =Main.itemsList[index].offsetLeft - Main.offsetLeft_scrollLeft;
            if(distance>=0){
                $('.musicBox').scrollLeft(distance);
            }else{
                $('.musicBox').scrollLeft(0);
            }
    }
    //计算当前屏幕中间位置的音乐项的index
    function computeCenterIndex(){
        return parseInt(($('.musicBox').scrollLeft() + window.screen.width / 2 + Main.itemsList[0].offsetWidth / 2) / (Main.itemsList[1].offsetLeft - Main.itemsList[0].offsetLeft)-1);
    }
    //获取歌曲失败，弹窗提示
    window.popup = function (wen){
        $('.popup').text(wen);
        $('.popup').css({bottom:'3rem',opacity:'1'});
        setTimeout(() => {
            $('.popup').removeAttr('style');
        }, 1000);
    }
   
})